package com.sky.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.BaseException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishFlavorService;
import com.sky.service.DishService;
import com.sky.utils.AliOssUtil;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Resource
    private DishMapper DishMapper;
    @Resource
    private DishFlavorMapper DishFlavorMapper;
    @Resource
    private SetmealDishMapper setmealDishMapper;
    @Resource
    private DishFlavorService dishFlavorService;
    @Resource
    private SetmealMapper setmealMapper;
    @Resource
    private AliOssUtil aliOssUtil;

    @Override
    @Transactional
    public void saveDishWithFlavors(DishDTO dishDTO) {
        //保存一个菜品
        Dish dish = new Dish();
        //将DTO中的属性复制到dish对象中
        BeanUtils.copyProperties(dishDTO, dish);
        //存文件路径时存objectName
        dish.setImage(aliOssUtil.extractObjectKey(dishDTO.getImage()));
        DishMapper.insert(dish);
        //为该菜品保存多个口味
       dishFlavorService.insertDishFlavor(dishDTO, dish);
    }

    /**
     * 菜品分页查询
     */
    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {
        int current = dishPageQueryDTO.getPage();
        int pageSize = dishPageQueryDTO.getPageSize();
        Page<DishVO> pageQuery = new Page<>(current, pageSize);
        Page<DishVO> dishVOPage = DishMapper.pageDishWithCategory(pageQuery, dishPageQueryDTO);
        //将dishVoPage中的records中的image属性从objectName改为签名的临时路径
        for (DishVO dishVO : dishVOPage.getRecords()) {
            dishVO.setImage(aliOssUtil.generatePresignedUrl(dishVO.getImage()));
        }
        return new PageResult(dishVOPage.getTotal(), dishVOPage.getRecords());
    }

    /**
     * 批量删除菜品
     */
    @Override
    @Transactional
    public void deleteBatch(List<Long> ids) {
        //删除逻辑 1,如果菜品正在起售，则不能删除
       //ids中的这些菜品 有一个处于起售状态 就不能删除
        for (Long id : ids) {
            Dish dish = DishMapper.selectById(id);
            if (Objects.equals(dish.getStatus(), StatusConstant.ENABLE)) {
                throw new BaseException(MessageConstant.DISH_ON_SALE);
            }
        }
        //2,如果菜品有套餐关联，则不能删除
        //在setMealDish表中,根据dishId查询返回setMealDish列表
        List<Long> setmealDishIds = setmealDishMapper.selectSetmealIdsByDishId(ids);
        if (setmealDishIds != null && !setmealDishIds.isEmpty()) {
            throw new BaseException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }
        //3,删除菜品
        this.removeByIds(ids);
        //4,删除菜品关联的口味
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.in(DishFlavor::getDishId, ids);
        DishFlavorMapper.delete(dishFlavorLambdaQueryWrapper);

    }

    @Override
    public DishVO getByIdWithFlavor(Long id) {
        //获取菜品数据
        Dish dish = DishMapper.selectById(id);
        //获取菜品口味数据
        List<DishFlavor> dishFlavors = DishFlavorMapper.selectList(new LambdaQueryWrapper<DishFlavor>().eq(DishFlavor::getDishId, id));
        //封装VO数据返回
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(dishFlavors);
        dishVO.setImage(aliOssUtil.generatePresignedUrl(dish.getImage()));
        return dishVO;
    }

    @Override
    @Transactional
    public void update(DishDTO dishDTO) {
        //更新菜品数据
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setImage(aliOssUtil.extractObjectKey(dishDTO.getImage()));
        DishMapper.updateById(dish);
        //更新菜品口味数据 //先删除菜品口味数据
        LambdaQueryWrapper<DishFlavor> dishFlavorLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishFlavorLambdaQueryWrapper.eq(DishFlavor::getDishId, dishDTO.getId());
        DishFlavorMapper.delete(dishFlavorLambdaQueryWrapper);
        //再添加菜品口味数据
       dishFlavorService.insertDishFlavor(dishDTO, dish);
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        DishMapper.updateById(dish);
        //菜品停售时,与该菜品关联的套餐也要停售
        //在setmealDish表中,根据dishId查询返回setmealId列表 然后在setmeal表中批量更新
        if (Objects.equals(status, StatusConstant.DISABLE)) {
            List<Long> dishId = new ArrayList<>();
            dishId.add(id);
            List<Long> setmealIds = setmealDishMapper.selectSetmealIdsByDishId(dishId);
            //判空
            if (setmealIds != null && !setmealIds.isEmpty()) {
                //有套餐关联该菜品
                //通过id批量更新
                Setmeal setmeal = new Setmeal();
                setmeal.setStatus(StatusConstant.DISABLE);
                setmealMapper.update(setmeal, new LambdaQueryWrapper<Setmeal>().in(Setmeal::getId, setmealIds));

            }
        }

    }

    @Override
    public List<Dish> list(Long categoryId) {
        //通过分类id查询菜品数据
        //构造查询条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId, categoryId);
        //只能获取起售状态的菜品
        wrapper.eq(Dish::getStatus, StatusConstant.ENABLE);
        return DishMapper.selectList(wrapper);


    }

    @Override
    public List<DishVO> listWithFlavor(Dish dish) {
        //根据分类id查询菜品 并根据每个菜品查询出菜品口味数据
        //构造查询条件
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Dish::getCategoryId, dish.getCategoryId());
        wrapper.eq(Dish::getStatus, StatusConstant.ENABLE);
        List<Dish> DishList = DishMapper.selectList(wrapper);
        //遍历菜品列表,为每个菜品查询出菜品口味数据 封装进DishVo列表中
        List<DishVO> dishVOList = new ArrayList<>();
        for (Dish d : DishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d, dishVO);
            dishVO.setFlavors(DishFlavorMapper.selectList(new LambdaQueryWrapper<DishFlavor>().eq(DishFlavor::getDishId, d.getId())));
            dishVOList.add(dishVO);
        }
        return dishVOList;
    }
}
